import 'package:hive/hive.dart';
import '../model/training_record.dart';

class TrainingRecordRepository {
  late Box<TrainingRecord> _trainingRecordsBox;

  Future<void> init() async {
    _trainingRecordsBox = await Hive.openBox<TrainingRecord>('training_records');
  }

  Future<void> addRecord(TrainingRecord record) async {
    print('Adding record: ${record.toString()}');
    await _trainingRecordsBox.add(record);
    print('Record added successfully. Current count: ${_trainingRecordsBox.length}');
  }

  List<TrainingRecord> getAllRecords() {
    final records = _trainingRecordsBox.values.toList();
    print('Fetching all records. Count: ${records.length}');
    records.sort((a, b) => b.timestamp.compareTo(a.timestamp));
    return records;
  }

  List<TrainingRecord> getRecordsByType(String type) {
    return _trainingRecordsBox.values
        .where((record) => record.type == type)
        .toList()
        ..sort((a, b) => b.timestamp.compareTo(a.timestamp));
  }

  Future<void> clearRecords() async {
    await _trainingRecordsBox.clear();
  }

  Future<void> deleteRecord(int index) async {
    await _trainingRecordsBox.deleteAt(index);
  }
}